<!-- src/components/MyDialog.vue -->
<template>
  <div v-if="visible" class="dialog-mask">
    <div class="dialog-box">
      <p class="dialog-message">{{ message }}</p>
      <div class="dialog-buttons">
        <button v-if="showCancel" class="dialog-button" @click="onCancel">取消</button>
        <button v-if="showCancel" class="dialog-button" @click="onConfirm">确认</button>
        <button v-else class="dialog-button" @click="onConfirm">确定</button>
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'

const visible = ref(false)
const message = ref('')
const showCancel = ref(false)
let resolveFn: (val: boolean) => void

const open = (msg: string, cancel = false): Promise<boolean> => {
  message.value = msg
  showCancel.value = cancel
  visible.value = true
  return new Promise((resolve) => {
    resolveFn = resolve
  })
}

const onConfirm = () => {
  visible.value = false
  resolveFn(true)
}

const onCancel = () => {
  visible.value = false
  resolveFn(false)
}

// 供外部调用
defineExpose({ open })
</script>

<style scoped>
.dialog-mask {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.3);
  display: flex;
  justify-content: center;
  align-items: center;
  z-index: 9999;
}

.dialog-box {
  background-color: #fff;
  padding: 24px;
  border-radius: 8px;
  width: 320px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.2);
  text-align: center;
}

.dialog-message {
  margin-bottom: 20px;
  font-size: 16px;
  color: #333;
}

.dialog-buttons {
  display: flex;
  justify-content: center;
  gap: 16px;
}

.dialog-button {
  flex: 1;
  padding: 10px 0;
  border: none;
  border-radius: 4px;
  background-color: #409eff;
  color: white;
  font-size: 14px;
  cursor: pointer;
  user-select: none;
  transition: background-color 0.2s;
  min-width: 100px;
}

.dialog-button:hover {
  background-color: #66b1ff;
}
</style>
